package com.gears_software.sxdc.dccx.data.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.gears_software.sxdc.dccx.data.model.LineInfoModel;
import com.gears_software.sxdc.dccx.data.model.LocLocationModel;
import com.gears_software.sxdc.dccx.data.model.NoticeModel;
import com.gears_software.sxdc.dccx.data.model.PathRecord;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.EBean;

import java.sql.SQLException;

/**
 * Created by chezhenzhen on 2017/8/5.
 */
@EBean(scope = EBean.Scope.Singleton)
public class DataBaseHelper extends OrmLiteSqliteOpenHelper {
    public DataBaseHelper(Context context) {
        super(context, "carpool.db", null, 1);
    }

    Dao<NoticeModel, Integer> noticeDao;
    Dao<PathRecord, Integer> recordDao;
    Dao<LocLocationModel, Integer> locationDao;

    public Dao<NoticeModel, Integer> getNoticeDao() {
        if (noticeDao == null) {
            try {
                noticeDao = getDao(NoticeModel.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return noticeDao;
    }

    public Dao<PathRecord, Integer> getRecordDao() {
        if (recordDao == null) {
            try {
                recordDao = getDao(PathRecord.class);
            } catch (SQLException e) {

            }
        }
        return recordDao;
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, NoticeModel.class);
            TableUtils.createTable(connectionSource, PathRecord.class);

            TableUtils.createTable(connectionSource, LocLocationModel.class);
        } catch (SQLException e) {
            Logger.e(DataBaseHelper.class.getName(), "Unable to create datbases",
                    e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource, NoticeModel.class, true);
            TableUtils.dropTable(connectionSource, PathRecord.class, true);
            TableUtils.dropTable(connectionSource, LocLocationModel.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {
            Logger.e(DataBaseHelper.class.getName(),
                    "Unable to upgrade database from version " + i
                            + " to new " + i1, e);
        }
    }
}
